#Include 'Protheus.ch'

/*/{Protheus.doc} DTCOMA20
(long_description)
@author Microsiga
@since 18/12/2014
@version 1.0
@return ${return}, ${return_description}
@example
(examples)
@see (links_or_references)
/*/
User Function DTCOMA20(_cNumPC)
Local aArea		:= GetArea()
Local cQuery		:= ""
Local nRecnoSC7	:= 0
Local cAliasTmp	:= GetNextAlias()
Local dDatLib		:= Ctod(Space(8))
Local dDtEntreg	:= Ctod(Space(8))
Local aTamSx3 	:= TamSX3("CO1_XPRZEN")
Local nPrazo		:= 0
Local cCodEdt		:= ""
Local cNumPro		:= ""
Local cProgr		:= Alltrim(Upper(FunName()))

Default _cNumPC	:= SC7->C7_NUM

FKCOMMIT() //garantir a gravacao durante o transacao

cQuery += "SELECT SCR.CR_DATALIB, CO1.CO1_XPRZEN, SC7.C7_EMISSAO, SC7.R_E_C_N_O_ SC7RECNO FROM "+RetSQLName("SC7")+" SC7 "

cQuery += "LEFT JOIN " +RetSQLName("SCR") + " SCR ON SCR.D_E_L_E_T_ = ' ' AND "
cQuery += " SC7.C7_FILIAL = SCR.CR_FILIAL AND "
cQuery += " SC7.C7_NUM = SCR.CR_NUM AND "
cQuery += " SCR.CR_DATALIB <> ' ' AND "
cQuery += " SCR.CR_TIPO <> 'ED' "

cQuery += "LEFT JOIN " +RetSQLName("CO1") + " CO1 ON CO1.D_E_L_E_T_ = ' ' AND "
cQuery += " CO1.CO1_FILIAL = SC7.C7_FILIAL AND "
If cProgr $ "CNTA120.CNTA260"
	cCodEdt := CN9->CN9_CODED
	cNumPro := CN9->CN9_NUMPR
	cQuery += " CO1.CO1_CODEDT = '"+cCodEdt+"' AND CO1.CO1_NUMPRO = '"+cNumPro+"'  AND "
Else
	cQuery += " CO1.CO1_CODEDT = SC7.C7_CODED AND CO1.CO1_NUMPRO = SC7.C7_NUMPR AND "
EndIf
cQuery += " CO1.CO1_XPRZEN <> 0 "

cQuery += "WHERE SC7.D_E_L_E_T_ = ' ' AND "
If SC7->(FieldPos("C7_FISCORI")) == 0
	cQuery += "SC7.C7_FILIAL = '" +xFilial("SC7") +"' AND "
Else
	cQuery += "CASE SC7.C7_FISCORI WHEN '" +Space(FWSizeFilial()) +"' THEN SC7.C7_FILIAL "
	cQuery += "ELSE SC7.C7_FISCORI END = '" +xFilial("SC7") +"' AND "
EndIf
If cProgr != "CNTA120"
	cQuery += "SC7.C7_CODED <> ' ' AND SC7.C7_NUMPR <> ' ' AND "
Endif
cQuery += " SC7.C7_NUM = '"+ _cNumPC +"'  "

cQuery := ChangeQuery(cQuery)
dbUseArea( .T., "TOPCONN", TcGenQry(,,cQuery),cAliasTmp, .T., .F. )

TcSetField(cAliasTmp, "CO1_XPRZEN", aTamSx3[3], aTamSx3[1], aTamSx3[2])
TcSetField(cAliasTmp, "CR_DATALIB", "D", 08, 0)
TcSetField(cAliasTmp, "C7_EMISSAO", "D", 08, 0)

While (cAliasTmp)->(!Eof())
	dDatLib	:= If(!Empty((cAliasTmp)->CR_DATALIB),(cAliasTmp)->CR_DATALIB,(cAliasTmp)->C7_EMISSAO)
	nPrazo 	:= (cAliasTmp)->CO1_XPRZEN
	If nPrazo > 0
		dDtEntreg	:= (dDatLib + nPrazo)
		If nRecnoSC7 != (cAliasTmp)->SC7RECNO
			nRecnoSC7 := (cAliasTmp)->SC7RECNO
			SC7->(DbGoto((cAliasTmp)->SC7RECNO))
			RecLock("SC7",.F.)
			SC7->C7_DATPRF := dDtEntreg
			MsUnlock()
		EndIf
	EndIf
	(cAliasTmp)->(dbSkip())
EndDo

(cAliasTmp)->(dbCloseArea())
RestArea(aArea)
Return


